/**
 * 系统日志工具
 */

import { db } from '../db';
import { systemLogs } from '../db/schema';
import { createId } from '@paralleldrive/cuid2';

export interface SystemLogData {
  level: 'info' | 'warn' | 'error' | 'debug';
  module: string;
  action: string;
  message: string;
  userId?: string;
  username?: string;
  ip?: string;
  userAgent?: string;
  requestId?: string;
  duration?: number;
  details?: any;
}

/**
 * 记录系统日志到数据库
 */
export async function logToDatabase(logData: SystemLogData): Promise<void> {
  try {
    await db.insert(systemLogs).values({
      id: createId(),
      level: logData.level,
      module: logData.module,
      action: logData.action,
      message: logData.message,
      userId: logData.userId,
      username: logData.username,
      ip: logData.ip,
      userAgent: logData.userAgent,
      requestId: logData.requestId,
      duration: logData.duration,
      details: logData.details ? JSON.stringify(logData.details) : null,
      createdAt: new Date().toISOString()
    });
  } catch (error) {
    console.error('Failed to log to database:', error);
  }
}

/**
 * 记录用户操作日志
 */
export async function logUserOperation(
  userId: string,
  username: string,
  module: string,
  action: string,
  message: string,
  details?: any,
  ip?: string,
  userAgent?: string
): Promise<void> {
  await logToDatabase({
    level: 'info',
    module,
    action,
    message,
    userId,
    username,
    ip,
    userAgent,
    details
  });
}

/**
 * 记录系统错误日志
 */
export async function logSystemError(
  module: string,
  action: string,
  message: string,
  error: any,
  userId?: string,
  username?: string
): Promise<void> {
  await logToDatabase({
    level: 'error',
    module,
    action,
    message,
    userId,
    username,
    details: {
      error: error.message,
      stack: error.stack
    }
  });
}

/**
 * 记录认证相关日志
 */
export async function logAuthOperation(
  action: string,
  message: string,
  userId?: string,
  username?: string,
  ip?: string,
  userAgent?: string,
  success: boolean = true
): Promise<void> {
  await logToDatabase({
    level: success ? 'info' : 'warn',
    module: 'auth',
    action,
    message,
    userId,
    username,
    ip,
    userAgent
  });
}

/**
 * 记录数据库操作日志
 */
export async function logDatabaseOperation(
  action: string,
  table: string,
  recordId?: string,
  userId?: string,
  username?: string,
  details?: any
): Promise<void> {
  await logToDatabase({
    level: 'info',
    module: 'database',
    action,
    message: `${action} ${table}${recordId ? ` (ID: ${recordId})` : ''}`,
    userId,
    username,
    details
  });
}